#include "log_manager.hpp"
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <filesystem>
#include <chrono>
#include <ctime>

namespace async_logger {

LogManager::LogManager() : currentLogSize(0) {}

void LogManager::init(const std::string& processName) {
    this->processName = processName;
    std::filesystem::create_directories(getLogDirectory());
    currentDate = getCurrentDate();
}

void LogManager::rollLogIfNeeded() {
    std::string today = getCurrentDate();
    if (today != currentDate) {
        currentDate = today;
        currentLogSize = 0;
    }

    std::string logFilePath = getLogFilePath();
    if (std::filesystem::exists(logFilePath) && 
        std::filesystem::file_size(logFilePath) >= maxLogSize) {
        std::filesystem::rename(logFilePath, getRolledLogFilePath());
        currentLogSize = 0;
    }
}

std::string LogManager::getLogDirectory() const {
    return "./logs/" + processName;
}

std::string LogManager::getLogFilePath() const {
    return getLogDirectory() + "/" + currentDate + ".log";
}

std::string LogManager::getRolledLogFilePath() const {
    return getLogDirectory() + "/" + currentDate + "_" + getCurrentTime() + ".log";
}

std::string LogManager::getCurrentDate() const {
    auto now = std::chrono::system_clock::now();
    std::time_t now_c = std::chrono::system_clock::to_time_t(now);
    std::tm now_tm = *std::localtime(&now_c);
    std::ostringstream oss;
    oss << std::put_time(&now_tm, "%Y-%m-%d");
    return oss.str();
}

std::string LogManager::getCurrentTime() const {
    auto now = std::chrono::system_clock::now();
    std::time_t now_c = std::chrono::system_clock::to_time_t(now);
    std::tm now_tm = *std::localtime(&now_c);
    std::ostringstream oss;
    oss << std::put_time(&now_tm, "%H-%M-%S");
    return oss.str();
}

} // namespace async_logger